using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Xml;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using Argotic.Syndication;
using ud_Forum.Business;

namespace mojoPortal.Web.FeedUI
{
	public partial class RssForumFeed : Page
	{
		private int maxDaysOld = 90;
        private int moduleId = -1;
        private int pageId = -1;
        private int itemId = -1;
        private int threadId = -1;
        private string navigationSiteRoot = string.Empty;
        private string imageSiteRoot = string.Empty;
	    private string cssBaseUrl = string.Empty;
        private int entriesLimit = 90;
        private int entryCount;
        private string baseUrl = string.Empty;
        private SiteSettings siteSettings;
        private PageSettings pageSettings;
        private Module module;
        private Hashtable moduleSettings;
        private Guid securityBypassGuid = Guid.Empty;
        private bool canView;

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadSettings();

            if (canView)
            {
                RenderRss();
            }
            else
            {
                RenderError("Invalid Request");
            }
        }

        private void RenderRss()
        {
            RssForum rssForum = new RssForum
                                    {
                                        SiteId = siteSettings.SiteId,
                                        ModuleId = moduleId,
                                        PageId = pageId,
                                        ItemId = itemId,
                                        ThreadId = threadId,
                                        MaximumDays = maxDaysOld
                                    };

            RssFeed feed = new RssFeed();
            RssChannel channel = new RssChannel {Generator = "mojoPortal Forum module"};
            feed.Channel = channel;
            
            using (IDataReader posts = rssForum.GetPostsForRss())
            {
                while ((posts.Read()) && (entryCount <= entriesLimit))
                {
                    RssItem item = new RssItem
                                       {
                                           Title = posts["Subject"].ToString(),
                                           Description =
                                               SiteUtils.ChangeRelativeUrlsToFullyQuailifiedUrls(navigationSiteRoot,
                                                                                                 imageSiteRoot,
                                                                                                 posts["Post"].ToString()),
                                           PublicationDate = Convert.ToDateTime(posts["PostDate"])
                                       };

                    string target = baseUrl;

                    if (target.IndexOf("&thread=") < 0 && target.IndexOf("?thread=") < 0)
                    {
                        target += target.IndexOf("?") < 0
                                      ? "?thread=" + posts["ThreadID"] + "#post" + posts["PostID"]
                                      : "&thread=" + posts["ThreadID"] + "#post" + posts["PostID"];
                    }
                    item.Link = new Uri(target);

                    RssGuid g = new RssGuid(target, true);
                    item.Guid = g;

                    item.Author = posts["StartedBy"].ToString();

                    channel.AddItem(item);
                    entryCount += 1;

                }
            }

            Response.Cache.SetExpires(DateTime.Now.AddMinutes(5));
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.ContentType = "application/xml";

            Encoding encoding = new UTF8Encoding();
            Response.ContentEncoding = encoding;

            using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding))
            {
                xmlTextWriter.Formatting = Formatting.Indented;

                //////////////////
                // style for RSS Feed viewed in browsers
                if (ConfigurationManager.AppSettings["RSSCSS"] != null)
                {
                    string rssCss = ConfigurationManager.AppSettings["RSSCSS"];
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>");

                }

                if (ConfigurationManager.AppSettings["RSSXsl"] != null)
                {
                    string rssXsl = ConfigurationManager.AppSettings["RSSXsl"];
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>");

                }
                ///////////////////////////

               
                feed.Save(xmlTextWriter);

            }

        }

        private void LoadSettings()
        {
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            pageSettings = CacheHelper.GetCurrentPage();
            pageId = WebUtils.ParseInt32FromQueryString("pageid", -1);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", -1);
            itemId = WebUtils.ParseInt32FromQueryString("ItemID", -1);
            threadId = WebUtils.ParseInt32FromQueryString("thread", -1);
            securityBypassGuid = WebUtils.ParseGuidFromQueryString("g", securityBypassGuid);
            module = GetModule();

            if ((moduleId == -1) || (module == null) || (siteSettings == null)) { return; }

            bool bypassPageSecurity = false;

            if ((securityBypassGuid != Guid.Empty) && (securityBypassGuid == WebConfigSettings.InternalFeedSecurityBypassKey))
            {
                bypassPageSecurity = true;
            }

            if(
                (bypassPageSecurity)
                ||(WebUser.IsInRoles(pageSettings.AuthorizedRoles))
                || (WebUser.IsInRoles(module.ViewRoles))
                )
            {
                canView = true;
            }

            if (!canView) { return; }

            baseUrl = Request.Url.ToString().Replace("RSS.aspx", "Thread.aspx");

            if (WebConfigSettings.UseFoldersInsteadOfHostnamesForMultipleSites)
            {
                navigationSiteRoot = SiteUtils.GetNavigationSiteRoot();
                imageSiteRoot = WebUtils.GetSiteRoot();
                cssBaseUrl = imageSiteRoot;

            }
            else
            {
                navigationSiteRoot = WebUtils.GetHostRoot();
                imageSiteRoot = navigationSiteRoot;
                cssBaseUrl = WebUtils.GetSiteRoot();

            }

           
            moduleSettings = ModuleSettings.GetModuleSettings(moduleId);

            maxDaysOld = WebUtils.ParseInt32FromHashtable(moduleSettings, "RSSFeedMaxDaysOldSetting", 90);

            entriesLimit = WebUtils.ParseInt32FromHashtable( moduleSettings, "RSSFeedMaxPostsSetting", 90);
        }

		private void RenderError(string message)
		{
			Response.Write(message);
		}

		private Module GetModule() 
		{
			
            if (pageSettings != null)
            {
                foreach (Module getModule in pageSettings.Modules)
                {
                    if (getModule.ModuleId == moduleId)
                        return getModule;
                }
            }
			return null;
		}

		
	}
}
